<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class User extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->is_logged_in();
        if ($this->session->userdata('role') != 0) {
            show_error('Permission Denied', 500);
        }
        $this->load->model('user/user_model', 'user_model');
    }

    public function index() {
        $users = $this->user_model->find_all();
        $this->_data['users'] = $users;
        $this->load->admintemplate('list', $this->_data);
    }

    public function add() {
        $this->load->library('form_validation');
        $this->config->load('form_validate', TRUE);
        $this->form_validation->set_rules($this->config->item('user', 'form_validate'));

        if ($this->form_validation->run() == FALSE) {
            $this->load->admintemplate('add', $this->_data);
        } else {
            $params['username'] = $this->input->post('username', TRUE);
            $params['password'] = $this->encode_pwd($this->input->post('password', TRUE));
            $params['email'] = $this->input->post('email', TRUE);
            //$params['role_type'] = $this->input->post('role', TRUE);

            $this->user_model->insert($params);
            redirect('user');
        }
    }

    public function edit($id) {

        $this->_data['user'] = $this->user_model->find_id($id);

        $this->load->library('form_validation');
        $this->config->load('form_validate', TRUE);
        $this->form_validation->set_rules($this->config->item('useredit', 'form_validate'));

        if ($this->form_validation->run() == FALSE) {
            $this->load->admintemplate('edit', $this->_data);
        } else {
            $pwd = $this->input->post('password', TRUE);
            if ($pwd != '') {
                $params['password'] = $this->encode_pwd($pwd);
            }
            $params['email'] = $this->input->post('email', TRUE);
            //$params['role_type'] = $this->input->post('role', TRUE);

            $this->user_model->update($id, $params);
            redirect('user');
        }
    }

    public function delete() {
        $id = $this->input->post('id');
        echo $this->user_model->delete($id);
        die;
    }

    public function user_check($str) {
        if ($str == 'test') {
            $this->form_validation->set_message('user_check', 'The %s field can not be the word "test"');
            return FALSE;
        } else {
            $this->form_validation->set_message('user_check', 'The %s field can not be the word "test"');
            return FALSE;
        }
    }

}
